﻿// Copyright 2009 Mike Geise
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace Falcon.Forums.Domain.Extensions
{
	using System;
	using System.Collections.Generic;
	using System.Globalization;
	using System.Web;
	using System.Web.Mvc;
	using Falcon.Core.Extensions;
	using Falcon.Forums.Domain.Enums;

	public static class ForumExtension
	{
		// constants
		public const string ForumNew = "forum_new";
		public const string ForumOld = "forum_old";
		public const string ForumNewClosed = "forum_new_closed";
		public const string ForumOldClosed = "forum_old_closed";

		/// <summary>
		/// Initializes the <see cref="ForumExtension"/> class.
		/// </summary>
		static ForumExtension()
		{
			Localized = new Dictionary<string, string>
			{
				{ ForumNew, ForumsResources.Titles.NewPosts },
				{ ForumOld, ForumsResources.Titles.NoNewPosts },
				{ ForumNewClosed, ForumsResources.Titles.ClosedNewPosts },
				{ ForumOldClosed, ForumsResources.Titles.ClosedNoNewPosts }
			};
		}

		/// <summary>
		/// Gets or sets the localized.
		/// </summary>
		/// <value>The localized.</value>
		private static Dictionary<string, string> Localized
		{
			get;
			set;
		}

		/// <summary>
		/// Gets the status icon for the forum.
		/// </summary>
		/// <param name="forum">The forum.</param>
		/// <returns></returns>
		public static string StatusImage(this Forum forum)
		{
			var context = HttpContext.Current;
			var name = string.Concat("forum_read_", forum.Id);
			var cookie = context.Request.Cookies[name];
			var read = true;

			if (cookie != null)
			{
				if (forum.LastPost != null && DateTime.Now.Subtract(forum.LastPost.Created).Days < ForumsSettings.DaysReadExpire)
				{
					read = DateTime.Parse(cookie.Value, CultureInfo.InvariantCulture) > forum.LastPost.Updated;
				}
			}

			string key;

			if (forum.Status == ForumStatus.Closed)
			{
				key = read ? ForumOldClosed : ForumNewClosed;
			}
			else
			{
				key = read ? ForumOld : ForumNew;
			}

			var builder = new TagBuilder("img");
			var text = Localized[key];

			builder.MergeAttribute("src", string.Concat(ForumsSettings.IconPath.AsRoot(), "/", key, ".gif"));
			builder.MergeAttribute("alt", text);
			builder.MergeAttribute("title", text);

			return builder.ToString(TagRenderMode.SelfClosing);
		}
	}
}